//
//  YMDeviceScanQRCodeVC.m
//  YMMedical
//
//  Created by y s on 2023/7/17.
//

#import "YMDeviceScanQRCodeVC.h"
#import <AVFoundation/AVFoundation.h>
#import "UINavigationController+FDFullscreenPopGesture.h"

@interface YMDeviceScanQRCodeVC ()<AVCaptureMetadataOutputObjectsDelegate, CALayerDelegate>

@property (nonatomic, strong) UIButton *btnBack;
@property (nonatomic, strong) UIImageView *imgvScan;
@property (nonatomic, strong) UIImageView *imgvLine;

@property (nonatomic, strong) AVCaptureDevice *device;
@property (nonatomic, strong) AVCaptureDeviceInput *input;
@property (nonatomic, strong) AVCaptureMetadataOutput *output;
@property (nonatomic, strong) AVCaptureSession *session;

@property (nonatomic, strong) AVCaptureVideoPreviewLayer *preview;
@property (nonatomic, strong) CALayer *maskLayer;

@property (nonatomic, assign) CGFloat boxHeight;




@end

@implementation YMDeviceScanQRCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _boxHeight = [SFitUtil fit:100];
    if (_isCard){
        _boxHeight = [SFitUtil fit:345];
    }
    [self setUI];
    [self setScanQR];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.isWhiteStatusBar = YES;
    // 添加扫描线以及开启扫描线的动画
    [self startAnimate];
    // 开启二维码扫描
    WEAK_SELF;
    dispatch_queue_t serialQueue = dispatch_queue_create("com.scan.gcdqueue.recordVideo", DISPATCH_QUEUE_SERIAL);
    dispatch_async(serialQueue, ^{
        //开始运行session
        if (weakSelf.session.running == NO){
            [weakSelf.session startRunning];
        }
    });
}

#pragma mark -- UI
- (void)setUI{
    self.navBarHidden = YES;
    self.fd_interactivePopDisabled = YES;
//    self.view.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:self.btnBack];
    [self.view addSubview:self.imgvScan];
    [self.btnBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(24+22, NAV_BAR_HEIGHT));
        make.top.mas_equalTo(STATUS_BAR_HEIGHT);
    }];
    [self.imgvScan mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo([SFitUtil fit:60]+TOP_BAR_HEIGHT);
        make.height.mas_equalTo(_boxHeight);
        make.width.mas_equalTo([SFitUtil fit:345]);
    }];

}

- (void)setScanQR{
    
    _session = [[AVCaptureSession alloc] init];
    //高质量采集
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    if ([_session canAddInput:self.input]) {
        [_session addInput:self.input];
    }
    if ([_session canAddOutput:self.output]) {
        [_session addOutput:self.output];
    }
    // 设置条码类型为二维码
    [self.output setMetadataObjectTypes:[self metadataObjectType]];
    
    // 设置扫描范围
    [self setOutputInterest];
    
    // 3、实时获取摄像头原始数据显示在屏幕上
    _preview = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame = self.view.layer.bounds;
    self.view.layer.backgroundColor = [[UIColor blackColor] CGColor];
    [self.view.layer insertSublayer:_preview atIndex:0];
    
    self.maskLayer = [[CALayer alloc]init];
    self.maskLayer.frame = self.view.layer.bounds;
    self.maskLayer.delegate = self;
    [self.view.layer insertSublayer:self.maskLayer above:_preview];
    [self.maskLayer setNeedsDisplay];
}
//设置二维码的扫描范围
- (void)setOutputInterest{
    CGSize size = self.view.bounds.size;
    CGFloat scanWidth = [SFitUtil fit:345];
    CGFloat scanHeight = _boxHeight;
    CGFloat scanX = (size.width - scanWidth) / 2;
    CGFloat scanY = [SFitUtil fit:60]+TOP_BAR_HEIGHT;
    CGFloat p1 = size.height/size.width;
    CGFloat p2 = 1920./1080.; //使用了1080p的图像输出
    if (p1 < p2) {
        CGFloat fixHeight = size.width * 1920. / 1080.;
        CGFloat fixPadding = (fixHeight - size.height)/2;
        _output.rectOfInterest = CGRectMake((scanY + fixPadding) / fixHeight,
                                            scanX / size.width,
                                            scanHeight / fixHeight,
                                            scanWidth / size.width);
    } else {
        CGFloat fixWidth = self.view.bounds.size.height * 1080. / 1920.;
        CGFloat fixPadding = (fixWidth - size.width)/2;
        _output.rectOfInterest = CGRectMake(scanY / size.height,
                                            (scanX + fixPadding) / fixWidth,
                                            scanHeight / size.height,
                                            scanWidth / fixWidth);
    }

}
- (void)startAnimate{
   
    CGFloat scanLineH = 7;
    self.imgvLine.frame = CGRectMake( 5, 0, [SFitUtil fit:335], scanLineH);
    [self.imgvScan addSubview:self.imgvLine];
    
    [UIView animateWithDuration:2.0 delay:0 options:UIViewAnimationOptionRepeat animations:^{
        self.imgvLine.frame = CGRectMake( 5, self.boxHeight-scanLineH, [SFitUtil fit:335], scanLineH);
    } completion:nil];
}

- (void)backAction:(id)sender{
    [SJumpUtil popVC:self animated:YES];
}

#pragma mark -- AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    NSString *stringValue = @"";
    [SHUD showWait:self.view];
    if ([metadataObjects count] > 0 ) {
        // 当扫描到数据时，停止扫描
        WEAK_SELF;
        dispatch_queue_t serialQueue = dispatch_queue_create("com.scan.gcdqueue.recordVideo", DISPATCH_QUEUE_SERIAL);
        dispatch_async(serialQueue, ^{
            //开始运行session
            if (weakSelf.session.running){
                [weakSelf.session stopRunning];
            }
        });
        // 将扫描的线从父控件中移除
        [self.imgvLine removeFromSuperview];
        
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
        if ([metadataObject respondsToSelector:@selector(stringValue)]){
            stringValue = metadataObject.stringValue;
        }
    }
    // 当前延迟1.0秒
    WEAK_SELF;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 隐藏遮盖
        [SHUD hide:weakSelf.view];
        if (weakSelf.backStep){
            [SJumpUtil popVC:weakSelf animated:NO];
        }else{
            [weakSelf backAction:nil];
        }
        if (weakSelf.finishBlock){
            weakSelf.finishBlock(stringValue);
        }
    });
}
#pragma mark - CALayerDelegate
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
    if (layer == self.maskLayer) {
        UIGraphicsBeginImageContextWithOptions(self.maskLayer.frame.size, NO, 1.0);
        CGContextSetFillColorWithColor(ctx, [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2].CGColor);
        CGContextFillRect(ctx, self.maskLayer.frame);
        CGRect scanFrame = [self.view convertRect:self.imgvScan.frame fromView:self.imgvScan.superview];
        CGContextClearRect(ctx, scanFrame);
    }
}
#pragma mark -- setter
- (UIButton *)btnBack{
    if (_btnBack == nil){
        _btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnBack setImage:[UIImage imageNamed:@"tools_nav_white_back"] forState:UIControlStateNormal];
        [_btnBack addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnBack;
}
- (UIImageView *)imgvScan{
    if (_imgvScan == nil){
        _imgvScan = [[UIImageView alloc] init];
        UIImage *img = [UIImage imageNamed:@"home_device_scanQR_box_icon"];
        img = [img resizableImageWithCapInsets:UIEdgeInsetsMake(40, 100, 40, 100) resizingMode:UIImageResizingModeStretch];
        _imgvScan.image = img;
        _imgvScan.backgroundColor = [SUIUtil colorOf:0x0 alpha:0.3];
    }
    return _imgvScan;
}
- (UIImageView *)imgvLine{
    if (_imgvLine == nil){
        _imgvLine = [[UIImageView alloc] init];
        _imgvLine.image = [UIImage imageNamed:@"home_scan_animation_line"];
    }
    return _imgvLine;
}
- (AVCaptureDevice *)device{
    if (!_device) {
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([_device lockForConfiguration:nil]) {
             //自动白平衡
             if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]) {
                 [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance];
             }
             //自动对焦
             if ([_device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
                 [_device setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
             }
             //自动曝光
             if ([_device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
                 [_device setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
             }
             [_device unlockForConfiguration];
        }
    }
    return _device;
}
- (AVCaptureDeviceInput *)input{
    if (!_input) {
        _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    }
    return _input;
}
- (AVCaptureMetadataOutput *)output{
    if (!_output) {
        _output = [[AVCaptureMetadataOutput alloc] init];
        [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    }
    return _output;
}

/** 根据扫描器类型配置支持编码格式 */
- (NSArray *)metadataObjectType{
    return @[AVMetadataObjectTypeQRCode,
             AVMetadataObjectTypeEAN13Code,
             AVMetadataObjectTypeEAN8Code,
             AVMetadataObjectTypeUPCECode,
             AVMetadataObjectTypeCode39Code,
             AVMetadataObjectTypeCode39Mod43Code,
             AVMetadataObjectTypeCode93Code,
             AVMetadataObjectTypeCode128Code,
             AVMetadataObjectTypePDF417Code];
}

- (void)dealloc{
    // 删除预览图层
    if (_preview) {
        [_preview removeFromSuperlayer];
    }
    if (self.maskLayer) {
        self.maskLayer.delegate = nil;
    }
}


@end
